<template>
  <a-menu
    v-model:selectedKeys="selectedKeys"
    mode="inline"
    theme="dark"
    :openKeys="openKeys"
    :style="{ height: '100%', borderRight: 0 }">
    <template
      v-for="menuItem in menuList"
      :key="index">
      <template v-if="!menuItem.hasOwnProperty('children')">
        <a-menu-item
          :key="menuItem.name"
          @click="onMenuClick(menuItem)">
          <template #icon>
            <Icon :icon="menuItem.meta.icon"/>
          </template>
          {{ menuItem.meta.title }}
        </a-menu-item>
      </template>
      <template v-else>
        <a-sub-menu
          :key="menuItem.name">
          <template #icon>
            <span :class="['dpifont',menuItem.meta.icon]"/>
          </template>
          <template #title>
            <span>{{ menuItem.meta.title }}</span>
          </template>
          <a-menu-item
            v-for="menuItemChild in menuItem.children"
            :key="menuItemChild.name"
            @click="onMenuClick(menuItemChild)">
            {{ menuItemChild.meta.title }}
          </a-menu-item>
        </a-sub-menu>
      </template>
    </template>
  </a-menu>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { menuList } from '@/router'
import { useStore } from 'vuex'
import Icon from './Icon.vue'

const store = useStore()
const route = useRoute()
const selectedKeys = ref([]) // 选中节点的keys
const router = useRouter() // 路由
const openKeys = ref([]); // 展开的keys
/**
 * 菜单点击
 * @param {Array} menu 第一个参数父路由或当前路由，如果存在第二个参数为当前路由
 * 路由跳转，保存当前路由关键字
 * 保存已经点击路由对象
 */
function onMenuClick ({ path }) {
  router.push(`/home/${path}`)
}

const activeMenu = computed(() => store.state.base.activeMenu)

watch(activeMenu, (v) => {
  selectedKeys.value[0] = v
})

watch(route, ({ name, path, meta }) => {
  // 默认展开节点
  menuList.forEach((value) => {
    if(value.children) {
      const menu = value.children.find((key) => key.name === name);
      const ekey = openKeys.value.find((key) => key === value.name);
      if (menu && !ekey) {
        openKeys.value.push(value.name);
      }
    }
  });
  store.commit('base/setActive', name)
  store.commit('base/setMenu', { title: meta.title, name, path, icon: meta.icon })
}, { deep: true, immediate: true })
</script>

<style lang="less" scoped>
@import "@/assets/style/dpifont/iconfont.css";
.ant-menu {
  background: transparent;
}
/deep/.ant-menu-sub.ant-menu-inline {
  background: transparent;
}
/deep/ .ant-menu-item-selected {
  background-color: #0455da !important;
}
</style>
